package kk.servlet;

import kk.domain.Book;
import kk.domain.PageBean;
import kk.service.BookService;
import kk.service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/client/bookServlet")
public class ClientBookServlet extends BaseServlet {
    private BookService bookService = new BookServiceImpl();
    protected void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //分页查询图书信息
        //默认第一页
        int currentPage=1;
        String currentPageStr = request.getParameter("currentPage");
        if (currentPageStr!=null){
            currentPage=Integer.parseInt(currentPageStr);
        }

        //默认每页显示四条数据
        int pageSize=4;
        String pageSizeStr = request.getParameter("pageSize");
        if (pageSizeStr!=null){
            pageSize=Integer.parseInt(pageSizeStr);
        }
        PageBean<Book> pageBean = bookService.page(currentPage,pageSize);
        pageBean.setUrl("/client/bookServlet?action=page");
        request.setAttribute("pageBean",pageBean);
        request.getRequestDispatcher("/pages/client/index.jsp").forward(request,response);

    }

    protected void pageByPrice(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //分页查询图书信息
        //默认第一页
        int currentPage=1;
        String currentPageStr = request.getParameter("currentPage");
        if (currentPageStr!=null){
            currentPage=Integer.parseInt(currentPageStr);
        }

        //默认每页显示四条数据
        int pageSize=4;
        String pageSizeStr = request.getParameter("pageSize");
        if (pageSizeStr!=null){
            pageSize=Integer.parseInt(pageSizeStr);
        }

        String minStr = request.getParameter("min");
        int min=0;//默认最小值为0
        if (minStr!=null && ""!=minStr){
            min=Integer.parseInt(minStr);
        }

        String maxStr = request.getParameter("max");
        int max=Integer.MAX_VALUE; //默认最大的价格
        if (maxStr!=null && ""!=maxStr){
            max=Integer.parseInt(maxStr);
        }

        PageBean<Book> pageBean = bookService.pageByPrice(currentPage,pageSize,min,max);
        StringBuilder sb=new StringBuilder("/client/bookServlet?action=pageByPrice");
        if (minStr!=null && minStr!=""){
            sb.append("&min=").append(min);
        }

        if (maxStr!=null && maxStr!=""){
            sb.append("&max=").append(max);
        }
        pageBean.setUrl(sb.toString());
        request.setAttribute("pageBean",pageBean);
        request.getRequestDispatcher("/pages/client/index.jsp").forward(request,response);

    }
}
